import Vue from "vue";
import Vuex from "vuex";
// import SockJS from "sockjs-client";
// import Stomp from "stompjs";
Vue.use(Vuex);
export default new Vuex.Store({
  state: {
    //
    // socket = new WebSocket("ws://10.0.204.143:18880/gdw/netty/ws/witness/project/updateProject");
    url: ``,
    checkInterval: null, // 断线重连时 检测连接是否建立成功
    websocket: null,
    stompClient: null,
    listenerUrlArr: [], // 所有需要订阅的url通道（包含已经订阅的和未订阅的），用于断线重连时，重新建立通道
    subscribedUrlArr: [], // 已经订阅的url通道, 避免重复订阅通道
    wsData: {}, // 订阅通道返回的数据
    nettyData: {}, // 返回的数据
    reconnectNums: 0 // 失败重连次数---默认0，设置超过10次不再重连
  },
  getters: {
    wsData(state) {
      return state.wsData;
    },
    nettyData(state) {
      return state.nettyData;
    }
  },
  mutations: {
    websocketDisconnect(state) {
      state.stompClient.disconnect(() => {
        console.log("ws结束");
      });
    },
    websocketClose(state, p) {
      console.log("p", p);
      console.log("state.socket", state.socket);
      console.log("WebSocket.OPEN", WebSocket.OPEN);
      if (state.socket && state.socket.readyState === WebSocket.OPEN) {
        // close方法不能传参数，会报错
        state.socket.close();
      }
    },
    websocketInit(state, url) {
      console.log("进来了------------netty", url);
      console.log("netty state.socket", state.socket);
      state.url = url || `ws://${location.host}/gdw/netty/ws/witness/project/updateProject`;
      if (!state.socket || state.socket.readyState !== WebSocket.OPEN) {
        this.commit("websocketConnect");
      }
    },
    websocketConnect(state) {
      // ws://10.0.204.143:18880
      // location.host
      console.log("netty init");
      // state.nettyData[state.url] = {};
      state.socket = new WebSocket(state.url);
      state.socket.onmessage = function (event) {
        console.log("netty event.data", event.data);
        const res = JSON.parse(event.data);
        console.log("netty ocket消息==============", res);
        // 多个ws接口，返回对应的数据
        if (state.url === `ws://${location.host}/gdw/netty/ws/witness/project/updateProject`) {
          res.time = new Date(); // 处理重复更新同一条数据
          state.wsData = res;
        } else {
          state.nettyData = res;
        }
        // Vue.$set(state.nettyData, state.url, res);
        // state.nettyData[state.url] = res;
      };
      state.socket.onopen = (event) => {
        console.log("netty WebSocket连接建立成功！", event);
        const msgObj = {
          WITNESS_PROJECT_WS: "WITNESS_PROJECT_WS"
          // witnessUserId: sessionStorage.getItem("userId")
        };
        this.commit("websocketSend", JSON.stringify(msgObj));
      };
      state.socket.onclose = function (p) {
        console.log("netty p", p);
        console.log("netty WebSocket连接关闭");
      };
      // ---------------
    },
    websocketSend(state, p) {
      if (!window.WebSocket) {
        return;
      }
      if (state.socket.readyState === WebSocket.OPEN) {
        state.socket.send(p);
      } else {
        console.log("WebSocket连接没有建立成功！");
      }
    },
    // 订阅ws通道
    websocketSubscribe(state, listenerUrl) {
      console.log("state-netty", state);
      console.log("listenerUrl-netty", listenerUrl);
      // if (state.listenerUrlArr.indexOf(listenerUrl) === -1) {
      //   state.listenerUrlArr.push(listenerUrl);
      // }
      if (state.stompClient && state.stompClient.connected) {
        // if (state.subscribedUrlArr.indexOf(listenerUrl) === -1) {
        //   state.subscribedUrlArr.push(listenerUrl);
        //   state.stompClient.subscribe(listenerUrl, (msg) => {
        //     const res = JSON.parse(msg.body);
        //     console.log("socket消息==============", res);
        //     res.time = new Date(); // 处理重复更新同一条数据
        //     state.wsData = res;
        //   });
        // }
      } else {
        this.commit("websocketInit", listenerUrl);
        // this.commit("websocketInit", state.url);
      }
    }
  },
  actions: {
    websocketDisconnect({ commit }) {
      commit("websocketDisconnect");
    },
    websocketInit({ commit }, url) {
      console.log("netty-url", url);
      commit("websocketInit", url);
    },
    websocketSend({ commit }, p) {
      commit("websocketSend", p);
    },
    websocketClose({ commit }, p) {
      // state.socket = null;
      commit("websocketClose", p);
    },
    // websocketUnsubscribe({ commit }, listenerUrl) {
    //   commit("websocketUnsubscribe", listenerUrl);
    // },
    websocketSubscribe({ commit }, listenerUrl) {
      commit("websocketSubscribe", listenerUrl);
    }
  }
});
